<?php

namespace app\api\controller;

use app\admin\model\Auditlog;
use app\admin\model\SystemConfig;
use app\admin\model\Withdrawals;
use app\admin\model\Worktags;
use app\admin\validate\Details;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\MoneyLog;
use fast\Random;
use think\Config;
use think\Db;
use think\Request;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 授权登录
     */



    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
//    public function login()
//    {
//        $account = $this->request->post('account');
//        $password = $this->request->post('password');
//        if (!$account || !$password) {
//            $this->error(__('Invalid parameters'));
//        }
//        $ret = $this->auth->login($account, $password);
//        if ($ret) {
//            $data = ['userinfo' => $this->auth->getUserinfo()];
//            $this->success(__('Logged in successful'), $data);
//        } else {
//            $this->error($this->auth->getError());
//        }
//    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }



    public function user_info()
    {
        $user = \app\admin\model\User::where('id', '=', $this->auth->id)->field('introduction,avatar,nickname,id,mobile,IFNULL((select name from fa_area where id=province),"") province,IFNULL((select name from fa_area where id=city),"") city,IFNULL((select name from fa_area where id=district),"") district,address,money,province provinceid,city cityid,district districtid')->find();

        $details = \app\admin\model\Details::where('user_id', '=', $user['id'])->order('id desc')->where('login_status', '=', '正常')
            ->find();
        if($details){
            $user['role']=$details['role'];
            $user['contract']=$details['signature_url']==null?0:1;
        }else{
            $user['order_count']=   \app\admin\model\Order::where('user_id','=',$user['id'])->where('order_status','=',1)->count();
            $user['role']='user';
        }


        $this->success('请求成功', $user);
    }


    public function  signature_url(){
        $signature_url = input('signature_url');
        $auditlog=Auditlog::where('user_id','=',$this->auth->id)->order('id desc')->find();
        if($auditlog['contract']==1){
            $this->error('订单已签名');
        }
        $auditlog=Auditlog::where('id','=',$auditlog['id'])->order('id desc')->update(['contract'=>1,'signature_url'=>$signature_url]);
        if($auditlog){
            $this->success('请求成功',[]);
        }else{
            $this->error('请求失败',[]);
        }

    }

    /**
     * 保存个人信息
     */
    public function save()
    {

        // 检查并获取头像
        if ($avatar = input('avatar')) {
            $data['avatar'] = $avatar;
        }
        // 检查并获取昵称
        if ($nickname = input('nickname')) {
            $data['nickname'] = $nickname;
        }
        if ($mobile = input('mobile')) {
            $data['mobile'] = $mobile;
        }
        if ($province = input('province')) {
            $data['province'] = $province;
        }
        if ($city = input('city')) {
            $data['city'] = $city;
        }
        if ($district = input('district')) {
            $data['district'] = $district;
        }
        if ($address = input('address')) {
            $data['address'] = $address;
        }
        if ($introduction = input('introduction')) {
            $data['introduction'] = $introduction;
        }
        if (empty($data)) {
            $this->error('没有要更新的内容');

        }
        $user = $this->auth->getUser();

        if ($user->save($data)) {
            $this->success('修改成功');

        }
        $this->error('修改失败');
    }

    //入驻
    public function settled(){
        $data = input();
        $auditlogvalidator = new \app\admin\validate\Auditlog();
        if (!$auditlogvalidator->check($data)) {
            $this->error('修改失败', $auditlogvalidator->getError());
        }
        $data['user_id']=$this->auth->id;

        $count=\app\admin\model\Auditlog::where('user_id','=', $data['user_id'])->where('audit_status','=','待审核')->count();
        if($count>0){
            $this->error('有待审核的记录，请勿重复提交');
        }

        $phone=\app\admin\model\Details::where('user_id','<>', $data['user_id'])->where('phone','=',$data['phone'])->count();
        if($phone>0){
            $this->error('此手机号已申请');
        }
        $data['createtime']=time();
        $data['updatetime']=time();
        $result=db::name('user_auditlog')->strict(false)->insert($data);
        if($result){
            $this->success('提交成功，等待审核');
        }else{
            $this->error('提交失败');
        }

    }

    /*
     *入驻状态
     */
    public function settled_status(){
        $log=\app\admin\model\Auditlog::where('user_id','=',$this->auth->id)->order('id desc')->where('role','=',input('role'))->find();
        if($log){
            if($log['audit_status']=='已驳回'){
                $data['audit_status']=-1;
            }else if($log['audit_status']=='待审核'){
                if($log['contract']==1){
                    $data['audit_status']=2;
                }else{
                    $data['audit_status']=3;
                }
            }else{
                $data['audit_status']=1;
            }
        }else{
            $data['audit_status']=0;
        }
        $this->success('请求成功',$data);
    }

    /*
     * 入驻信息
     */
    public function auditlog_info(){
        $log=\app\admin\model\Auditlog::where('user_id','=',$this->auth->id)->order('id desc')->where('audit_status','=','已驳回')->where('role','=',input('role'))->find();
        $this->success('请求成功',$log);
    }

    public function settled_info(){


        $details=\app\admin\model\Details::where('user_id','=',$this->auth->id)->find();
        $work=Worktags::where('type','=',2)->select();


        $selectedIds = explode(',', $details['job_tags']);

        foreach ($work as &$item) {
            // 检查 work 中的每个 id 是否在 selectedIds 数组中
            if (in_array($item->id, $selectedIds)) {
                // 如果匹配，设置选中状态
                $item->selected = true; // 添加选中状态
            } else {
                $item->selected = false; // 没有匹配则未选中
            }
        }
        $details['certificate'] =explode(",", $details['certificate']);
        $details['profile_image'] =explode(",", $details['profile_image']);
//        $details['personal_video'] =explode(",", $details['personal_video']);
        $details['attachment'] =explode(",", $details['attachment']);

        $details['work']=$work;
        $this->success('请求成功',$details);
    }



    //获取邀请码
    public function getWxcode()
    {
        $Wechat = new Wechat();

        // 假设这是获取到的 Base64 编码的二维码
        $base64QRCode = $Wechat->getWxcode($this->auth->id);
        $user=\app\admin\model\User::where('id','=',$this->auth->id)->find();


        $base64QRCode = preg_replace('/^data:image\/png;base64,/', '', $base64QRCode);
        if (empty($base64QRCode)) {
            die('Base64字符串为空或失效');
        }

        // 将 Base64 字符串解码
        $qrcodeData = base64_decode($base64QRCode);
        if ($qrcodeData === false) {
            die('Base64解码失败');
        }

        // 创建图像从解码数据
        $qrcode = imagecreatefromstring($qrcodeData);
        if (!$qrcode) {
            die('二维码加载失败');
        }

        // 加载背景图
        $backgroundPath = './uploads/share.jpg'; // 背景图路径
        $background = imagecreatefromjpeg($backgroundPath);
        if (!$background) {
            die('背景图加载失败');
        }

        // 合并二维码与背景图
        $qrcodeWidth = imagesx($qrcode);
        $qrcodeHeight = imagesy($qrcode);
        $destX = max(imagesx($background) - $qrcodeWidth - 820, 0); // 右边距 20px
        $destY = max(imagesy($background) - $qrcodeHeight - 1120, 0); // 下边距 20px

        // 合并图像
        imagecopy($background, $qrcode, $destX, $destY, 0, 0, $qrcodeWidth, $qrcodeHeight);

        // 添加自定义文字
        $textColor = imagecolorallocate($background, 0, 0, 0); // 黑色文本
        $fontFile = $_SERVER['DOCUMENT_ROOT'] . '/fonts/simsun.ttc'; // 确保使用支持中文的字体
        if (!file_exists($fontFile)) {
            die('字体文件不存在：' . $fontFile);
        }
            $sys=SystemConfig::find();
        $content = $sys['share_title']; // 替换为你的实际内容

        // 合并昵称和内容
        $lines = [
            $user['nickname'], // 第一行
            $content           // 第二行
        ];

//        $text = $user['nickname'].$content; // 要添加的文本
//        $fontSize = 50; // 字体大小



        // 设置边距
        $paddingX = 200; // X方向的边距
        $paddingY = 2000; // Y方向的边距

        // 逐行绘制文本
        $fontSize = 50; // 字体大小
        $lineHeight = $fontSize + 40; // 增加行高，调整上下行间距
        $y = $paddingY; // 当前的 Y 坐标

        foreach ($lines as $line) {
            $bbox = imagettfbbox($fontSize, 0, $fontFile, $line); // 获取文本边界框
            $textHeight = abs($bbox[1] - $bbox[7]); // 文本高度
            imagettftext($background, $fontSize, 0, $paddingX, $y + $textHeight, $textColor, $fontFile, $line);
            $y += $lineHeight; // 更新 Y 坐标
        }

        // 指定要保存的文件路径
        $savePath = './uploads/combined_image_'.$this->auth->id.'.jpg'; // 保存合成图像的路径

        // 启动输出缓冲区
        ob_start();

        // 输出合成图像到输出缓冲区
        imagejpeg($background); // 使用 imagejpeg 输出

        // 获取输出缓冲区的内容并编码为 Base64
        $imageData = ob_get_contents();
        ob_end_clean(); // 清理输出缓冲区

        // 将图像数据编码为 Base64
        $base64 = base64_encode($imageData);

        // 保存合成图像到服务器（覆盖同名文件）
        imagejpeg($background, $savePath); // 保存图像

        // 释放图像资源
        imagedestroy($background);
        imagedestroy($qrcode);

        // 构造完整的 URL，返回保存的图像地址
        $randomParam = rand(1000, 9999);
        $imageUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/uploads/combined_image_'.$this->auth->id.'.jpg?rand='. $randomParam; // 根据您的服务器配置调整
        $this->success('请求成功', ['img'=>$imageUrl]);

    }

    public function binding_bank(){
        $result=\app\admin\model\User::where('id','=',$this->auth->id)->update(['bank'=>input('bank'),'bankno'=>input('bankno')]);
        if($result!==false){
            $this->success('操作成功', []);
        }else{
            $this->error('操作失败');
        }
    }


    //提现
    public function tx()
    {
        $amount = $this->request->post('amount');
//        $bank = $this->request->post('bank');
//        $bankno= $this->request->post('bankno');


        Db::startTrans();
        $user = \app\common\model\User::where('id', '=', $this->auth->id)->lock(true)->find();
        if (($user['money'] - $amount < 0)) {
            DB::rollback();
            $this->error('余额不足');
        }
        if($amount<0.1||$amount>200){
            $this->error('提现范围0.1-200元');
        }
//        if($user['bankno']==null){
//            $this->error('请填写银行卡信息再操作');
//        }
//        if(!validateBankCard($bankno)){
//            $this->error('银行卡信息不正确');
//        }

        $Withdrawals = Withdrawals::where('user_id', '=', $this->auth->id)->lock(true)->find();
        $info = Withdrawals::create(['user_id' => $this->auth->id, 'amount' => $amount, 'method' => 'wechat' ]);
        Index::op_money($user['id'], $amount, 'dec', '提现', '提现', '提现',$info->id);
       if ($info) {
            DB::commit();
            $this->success('操作成功', []);
        }else{
           $this->error('余额失败');
       }
    }

    //余额日志
    public function money_log(){
       $list= MoneyLog::where('user_id','=',$this->auth->id)->order('id desc')->paginate(10);
        foreach ($list as $row) {
            $row['createtime_text'] = date('Y-m-d', $row['createtime']);
            $row['op']=$row['before']>$row['after']?'-':'+';
        }
        if ($list) {
            DB::commit();
            $this->success('操作成功', $list);
        }else{
            $this->error('余额失败');
        }
    }

    public function withdrawals_log(){
        $list= Withdrawals::where('user_id','=',$this->auth->id)->order('id desc')->paginate(10);
        foreach ($list as $row) {

        }
        if ($list) {
            DB::commit();
            $this->success('操作成功', $list);
        }else{
            $this->error('余额失败');
        }
    }





    //团队列表

    public function team_list() {
        // 获取当前用户的ID
        $currentUserId = $this->auth->id;

        $userinfo= \app\admin\model\User::where('id', $currentUserId)->find();

        // 获取所有一级用户（即当前用户的子用户）
        $firstLevelUsers = \app\admin\model\User::where('pid', $currentUserId)->select(); // 使用 select() 返回结果集
        $user1=0;
        $user2=0;
        // 初始化一个结果数组
        $users = [];

        // 添加一级用户到结果
        foreach ($firstLevelUsers as $user) {
            $users[] = [
                'id' => $user['id'],
                'name' => $user['nickname'],
                'avatar' => $user['avatar'],
                'level' => '直接',
                'pname'=>$userinfo['nickname'],
                'createtime' => date('Y-m-d H:i:s', $user['createtime'])
            ];
            $user1++;
            // 查询当前一级用户的二级用户
            $secondLevelUsers = \app\admin\model\User::where('pid', $user['id'])->select(); // 获取二级用户

            // 添加二级用户到结果
            foreach ($secondLevelUsers as $subUser) {
                $users[] = [
                    'id' => $subUser['id'],
                    'name' => $subUser['nickname'],
                    'avatar' => $subUser['avatar'],
                    'pname'=>$user['nickname'],
                    'level' =>'间接',
                    'createtime'=> date('Y-m-d H:i:s', $subUser['createtime'])
                ];
                $user2++;
            }
        }
        $data['total']=count($users);
        $data['user1']=$user1;
        $data['user2']=$user2;
        $data['data']=$users;
        $this->success('操作成功', $data);

    }


}
